<?php
namespace app\[MODULE]\controller;
use think\facade\Db;
use app\[MODULE]\model\[UTABLE] as [UTABLE]Model;
use app\common\BaseController;
use hg\apidoc\annotation as Apidoc;
use think\Request;
use think\exception\ValidateException;
use app\common\support\PHPExcelService;

class [CONTROLLER] extends BaseController{
    

    /**
     * @Apidoc\Title("列表")
     * @Apidoc\Url("[CONTROLLERLO]_index")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("page",type="int",desc="页码"),
     *   @Apidoc\Returned("limit",type="int",desc="查询数量"),
     *   @Apidoc\Returned("data",type="array",desc="返回数据"),
     *   @Apidoc\Returned("total",type="array",desc="数据总量")
     * )
     */
    public function index(Request $request){
        $page  = (int)$request->param('page/d', 0);
        $limit  = (int)$request->param('limit/d', 10);
        $search = request()->param();
        $where = [];
[SEARCH]
        $query  = [UTABLE]Model::where($where);
        $total  = $query->count();
        $data   = $query->page($page,$limit)->order('id desc')->select();

        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

    
        /**
     * @Apidoc\Title ("详情")
     * @Apidoc\Url("[CONTROLLERLO]_get")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("id", type="int", require=true, desc="id")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("data",type="string",desc="信息")
     * )
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = [UTABLE]Model::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }
        return $this->success('', $row);
    }

    /**
     * @Apidoc\Title("创建")
     * @Apidoc\Url("[CONTROLLERLO]_create")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("field1", type="string", require=false, desc="field1")
     * @Apidoc\Param("field2", type="string", require=false, desc="field2")
     * @Apidoc\Param("field3", type="string", require=false, desc="field3")
     */
       public function create(Request $request): \think\response\Json
    {
        $data = $request->post();
        try {
            $this->validate($data,[
[VALIDATEDATA]
            ],[
[VALIDATEMSG]
            ] );
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        $result = [UTABLE]Model::create($data);
        if ($result->isEmpty()) {
            return $this->error('错误');
        }

        return $this->success('成功');
    }



    /**
     * @Apidoc\Title("编辑")
     * @Apidoc\Url("[CONTROLLERLO]_edit")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("field1", type="string", require=false, desc="field1")
     * @Apidoc\Param("field2", type="string", require=false, desc="field2")
     * @Apidoc\Param("field3", type="string", require=false, desc="field3")
     */
    public function edit(){
        $data = request()->post();
         try {
             $this->validate($data,[
[VALIDATEDATA]
            ],[
[VALIDATEMSG]
            ] );
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        if(!$data['id']) return $this->error('缺少ID');
        if(![UTABLE]Model::where('id', $data['id'])->count()) return $this->error('数据不存在');
        if([UTABLE]Model::update($data,['id'=>$data['id']])) return $this->success('操作成功');
        return $this->error('操作失败');
    }





        /**
     * @Apidoc\Title ("删除")
     * @Apidoc\Url("[CONTROLLERLO]_delete")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int", require=true, desc="id")
     */
    public function delete(): \think\response\Json
    {
        $ids = request()->post('ids/s');
        $ids = explode(',', $ids);
        $row = [UTABLE]Model::where('id','in', $ids)->select();
        if (!$row) {
            return $this->error('错误');
        }
        $row->delete();
        return $this->success('成功');
    }

    //导出
     public function export_excell(){
        $search = request()->param();
        $where = [];
[SEARCH]
        $title = ['编号'];
        set_time_limit(0); // 设置超时时间
        $filename = '数据导出' . date('Ymdhis') . '.csv';
        header("Content-type:application/vnd.ms-csv");
        header('content-disposition:attachment; filename="' . $filename . '"');
        ob_end_flush();
        // ob_implicit_flush(true);
        // 写入导出标题
        echo iconv('utf-8', 'gbk', implode(',', $title)) . PHP_EOL;
        $lastId = 0;
        while (true) {
            $list =  [UTABLE]Model::where($where)->limit(100)->order('id asc')->where('id','>',$lastId)->select()->toArray();
            if (!empty($list)) {
                foreach ($list as $value) {
                    $item = []; // 初始化数组
                    // 用户信息
                    $item[] = $value['id']; // id
                    // 写入内容
                    echo iconv('utf-8', 'gbk//IGNORE', implode(',', $item)) . PHP_EOL;
                    $lastId = $value['id']; // 最大id
                }

            } else {
                break;
            }
        }
        exit;  
    }



        /**
     * 导入
     * @return void
     * @author Sam
     */
    public function import_excell(){
        if(empty($_FILES['file'])) json_response(0, '请选择文件');
        $list = big_csv_to_array($_FILES['file']['tmp_name']);
        try{
            $num = 0;
            if(count($list)){
                foreach($list as $k=>$v){
                    //根据业务自行处理数据
                    $data = [
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                $res =  [UTABLE]Model::create($data);
                if($res) $num++;
                }
            }
                return  $this->success('导入成功'.$num.'条数据');
            }catch(\Exception $e){
                return $this->error($e->getMessage());
            }
        }
}